package com.nowcoder.community.controller;

import com.nowcoder.community.annotation.LoginRequired;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.QiniuUtils;
import com.nowcoder.community.util.UserThreadLocal;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * @program: blog-parent
 * @description:
 * @author: hmx
 * @create: 2021-08-17 16:27
 **/
@Controller
@RequestMapping("/upload")
public class UploadController {

    @Resource
    private QiniuUtils qiniuUtils;

    @Resource
    private UserService userService;

    @Value("${qiniu.bucket.header.name}")
    private String headerBucketName;

    @Value("${qiniu.bucket.header.url}")
    public String headerBucketUrl;


    @LoginRequired
    @RequestMapping("/header")
    public String upload(MultipartFile headerImage, Model model) {
        if (headerImage == null) {
            model.addAttribute("error", "您还没有选择图片!");
            return "/site/setting";
        }

        String fileName = headerImage.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        if (StringUtils.isBlank(suffix)) {
            model.addAttribute("error", "文件的格式不正确!");
            return "/site/setting";
        }

        //原始文件名称 比如aa.png
        String originalFilename = headerImage.getOriginalFilename();
        //唯一的文件名称
        String fileName2 = UUID.randomUUID() + "." + StringUtils.substringAfterLast(originalFilename, ".");
        //上传文件到七牛云 云服务器 按量付费 速度快 把图片发放到离用户最近的服务器上
        //降低 我们自身应用服务器的带宽消耗

        boolean upload = qiniuUtils.upload(headerImage, fileName2, headerBucketName);
        if (upload) {
            String path = headerBucketUrl + fileName2;
            User user = UserThreadLocal.getUser();
            userService.updateHeader(user.getId(), path);
        }
        return "redirect:/index";
    }

}
